<template>
	<view class="long-press-container" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
		@touchend="handleTouchEnd">
		<!-- 触发区域 -->
		<view class="trigger-area" ref="triggerArea">
			<slot></slot>
		</view>

		<!-- 提示框主体 -->
		<view v-if="showTooltip" class="tooltip" :class="['tooltip-' + tooltipPosition, tooltipClass]"
			:style="[tooltipStyle, customStyle]">
			{{ tooltipText }}
		</view>

		<!-- 隐藏的测量元素 -->
		<view class="tooltip temp-measure" ref="measureElement" :style="{ 
            visibility: 'hidden',
            position: 'fixed',
            left: '-9999px',
            top: '-9999px',
            width: autoWidth ? 'auto' : computedMaxWidth
          }">
			{{ tooltipText }}
		</view>
	</view>
</template>

<script>
	export default {
		name: 'LongPressTooltip',
		props: {
			// 提示文本
			tooltipText: {
				type: String,
				default: '长按查看说明'
			},
			// 长按触发时间（毫秒）
			longPressDuration: {
				type: Number,
				default: 500
			},
			// 最大宽度（支持数字rpx/百分比）
			maxWidth: {
				type: [Number, String],
				default: '80vw'
			},
			// 是否自动宽度模式（根据内容自适应）
			autoWidth: {
				type: Boolean,
				default: true
			},
			// 自定义样式类名
			customClass: {
				type: String,
				default: ''
			},
			// 自定义内联样式
			customStyle: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			return {
				showTooltip: false,
				tooltipPosition: 'top',
				tooltipStyle: {},
				timer: null,
				triggerRect: {},
				contentWidth: 0
			}
		},
		computed: {
			// 处理maxWidth单位转换
			computedMaxWidth() {
				if (typeof this.maxWidth === 'number') {
					return `${this.maxWidth}rpx`
				}
				return this.maxWidth
			},
			// 合并样式类名
			tooltipClass() {
				return [
					this.customClass,
					{
						'auto-width': this.autoWidth
					}
				]
			}
		},
		mounted() {
			this.initMeasureElement()
		},
		methods: {
			// 初始化测量元素
			initMeasureElement() {
				const query = uni.createSelectorQuery().in(this)
				query.select('.temp-measure').boundingClientRect(data => {
					if (data) this.contentWidth = data.width
				}).exec()
			},

			// 处理触摸开始
			async handleTouchStart(e) {
				// 获取触发元素位置
				const query = uni.createSelectorQuery().in(this)
				query.select('.trigger-area').boundingClientRect(data => {
					this.triggerRect = data
				}).exec()

				// 设置长按定时器
				this.timer = setTimeout(async () => {
					// 获取屏幕信息
					const sysInfo = await uni.getSystemInfoSync()
					const screenWidth = sysInfo.screenWidth
					const screenHeight = sysInfo.screenHeight
					const touch = e.touches[0]

					// 计算可用空间
					const availableSpaceTop = touch.clientY
					const availableSpaceBottom = screenHeight - touch.clientY

					// 判断显示位置
					let verticalPosition = 'top'
					if (availableSpaceBottom > this.contentWidth + 20) {
						verticalPosition = 'bottom'
					}

					// 计算水平位置（居中显示）
					let left = touch.clientX - this.contentWidth / 2
					const maxLeft = screenWidth - this.contentWidth - 20
					const minLeft = 20
					left = Math.min(Math.max(left, minLeft), maxLeft)

					// 设置样式
					this.tooltipPosition = verticalPosition
					this.tooltipStyle = {
						top: verticalPosition === 'top' ?
							(touch.clientY - this.contentWidth - 10) + 'px' : (touch.clientY + 10) + 'px',
						left: left + 'px',
						maxWidth: this.computedMaxWidth,
						width: this.autoWidth ? 'auto' : this.computedMaxWidth
					}

					this.showTooltip = true
				}, this.longPressDuration)
			},

			// 处理触摸移动
			handleTouchMove() {
				if (this.timer) {
					clearTimeout(this.timer)
					this.timer = null
				}
				this.showTooltip = false
			},

			// 处理触摸结束
			handleTouchEnd() {
				if (this.timer) {
					clearTimeout(this.timer)
					this.timer = null
				}
				this.showTooltip = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	.long-press-container {
		width: 100%;
		position: relative;
		display: inline-block;
	}

	.trigger-area {
		/* padding: 20rpx;
		background-color: #f0f0f0;
		border-radius: 8rpx; */
		width: 100%;
		// white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tooltip {
		position: fixed;
		background: rgba(0, 0, 0, 0.7);
		color: #fff;
		padding: 12rpx 24rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		white-space: normal;
		word-break: break-word;
		z-index: 99999;
		pointer-events: none;
		transition: opacity 0.2s;
		max-width: 80vw;
		box-sizing: border-box;
		margin: 10rpx;
	}

	.tooltip.tooltip-top {
		transform: translateY(-100%);
	}

	.tooltip.tooltip-bottom {
		transform: translateY(10%);
	}

	.tooltip.auto-width {
		white-space: nowrap;
		min-width: 120rpx;
	}

	.temp-measure {
		padding: 12rpx 24rpx;
		font-size: 28rpx;
		word-break: break-word;
		white-space: pre-wrap;
	}
</style>